package com.wushi.lenovo.asia5b.app_di.other.presenter;

import android.text.TextUtils;

import com.mvp.base.BaseAppCompatActivity;
import com.mvp.base.BaseApplication;
import com.mvp.base.BasePresenter;
import com.mvp.base.NetParams;
import com.mvp.base.model.ResultModel;
import com.mvp.common.GlobalValue;
import com.mvp.common.LocalManageUtil;
import com.mvp.dagger.converter.ResponseConvertFactory;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.app_di.other.mvpview.H5ActivityView;
import com.wushi.lenovo.asia5b.app_event.FacebookEvent;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_http.TopupService;
import com.wushi.lenovo.asia5b.app_model.credit.bean.ThirdTopupType;
import com.wushi.lenovo.asia5b.app_model.h5.H5GoodBean;
import com.wushi.lenovo.asia5b.app_model.h5.H5WishBean;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_push.PushHelper;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;

import java.util.Map;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;


/**
 * Created by zhangyuncai on 2019/4/13.
 */
public class H5ActivityPresenter extends BasePresenter<H5ActivityView> {

    ApiService apiService;
    TopupService topupService;

    @Inject
    public H5ActivityPresenter(ApiService apiService, Retrofit retrofit, OkHttpClient okHttpClient) {
        this.apiService = apiService;
        retrofit = retrofit.newBuilder()
                .baseUrl(GlobalValue.BASE_PAYMENT_THIRD_URL)
                .addConverterFactory(ResponseConvertFactory.create(BaseApplication.sApplication))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        topupService = retrofit.create(TopupService.class);
    }

    //根据url地址查找商品id
    public void getProductIdByUrl(String url) {
        baseSubscribe(apiService.getProductIdByUrl(url, UserInfo.getMemberId()),
                resultModel -> {
                    getView().getProductIdByUrlResult(resultModel);
                });
    }


    //改变收藏状态
    public void changeWishType(H5WishBean h5WishBean) {
        boolean isWish = true;//收藏成功后的状态, true/false  收藏/非收藏
        Observable<ResultModel> observable = apiService.addWish(UserInfo.getMemberId(), h5WishBean.getGoods_id());
        if (TextUtils.equals(h5WishBean.getProduct_wishlist(), "1")) {//当前状态已收藏,那么就删除收藏
            observable = apiService.deleteWish(UserInfo.getMemberId(), h5WishBean.getGoods_id());
            isWish = false;
        }
        boolean finalIsWish = isWish;
        baseSubscribe(observable,
                resultModel -> {
                    getView().changeWishTypeResult(resultModel, h5WishBean, finalIsWish);
                });
    }

    //添加购物车
    public void addGoodMall(final H5GoodBean h5GoodBean, String url) {
        Map<String, Object> map = MapHelper.newHashMap();
        map.put("session_id", PushHelper.getRegistrationId());
        map.put("member_id", UserInfo.getMemberId() + "");
        map.put("product_id", h5GoodBean.getProdId());
        map.put("source", "1");
        map.put("type", "daigou");//这里写死代购,因为后台根据商品id自行判断
        map.put("option", h5GoodBean.getAttr());//这里不添加也行,因为后台根据商品id已经添加了
        map.put("remark", h5GoodBean.getRemark());
        map.put("device", "0");//Device Indicator, 1: IOS, 0: Android
        map.put("quantity", h5GoodBean.getQuantity() + "");//这里不添加也行,因为后台根据商品id已经添加了
        map.put("buy_now", h5GoodBean.getIs_buy_now());
        map.put("multiple_option", h5GoodBean.getMultiple_attr());
//        if (h5GoodBean.getMultiple_attr() != null) {
//            map.put("multiple_option", JsonUtil.INSTANCE.anyToJson(h5GoodBean.getMultiple_attr()));
//        }
        if (h5GoodBean.getGoods() != null) {
            if (TextUtils.equals(h5GoodBean.getGoods().getType(), "3")) {
                //这里不添加也行,因为后台根据商品id已经添加了
                map.put("type", "marketplace");
            }
        }
        baseSubscribe(apiService.addGoodMall(map), new NetParams("", "", false),
                resultModel -> {
                    getView().addGoodMallResult(resultModel, h5GoodBean.isBuyNow());
                    if (resultModel.isSuccess() && h5GoodBean.getGoods() != null) {
                        FacebookEvent.Companion.addCart(h5GoodBean.getGoods(), map);
                    }
                }
        );

    }


    //通过产品图片搜索商品
    public void searchProductBySnap(BaseAppCompatActivity activity, String path) {
        EyeUtils.uploadUrl(activity, path, s -> {
            if (!TextUtils.isEmpty(s)) {
                getView().searchProductBySnapResult(s);
            }
        });
    }

    //第三方充值
    public void thirdTopup(Map<String, Object> map, ThirdTopupType type) {
        if (map != null) {
            map.put("device", 0);//1 = IOS, 0 = Android
            map.put("language_code", LocalManageUtil.getAppLanguage() + "");
        }
        Disposable subscribe = topupService.thirdTopup(type.getTopupPath(), map)
                .doOnSubscribe(disposable -> {
                    getView().showLoadingBar(null);
                })
                .doAfterTerminate(() -> {
                    getView().dismissLoadingBar("");
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(responseBody -> {
                    getView().thirdTopupResult(responseBody);
                }, throwable -> {
                    throwable.printStackTrace();
                });
        composite.add(subscribe);
    }
}